<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/11
 * Time: 11:30
 */

class Comment_Model extends CI_Model
{

    private $totalSize = 0;

    /**
     * 初始化
     * CashMeal_Model constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }


    public function total()
    {
        return $this->totalSize;
    }

    /**
     * 获取评论列表
     * @param $goodsId
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public function lists($goodsId, $offset = 0, $limit = 20)
    {
        $db = clone($this->db);
        $db->select('c.id, c.userId, c.content, c.created, c.expressStars, c.goodsStars, c.anonymous');
        $db->where([
            'c.goodsId' => $goodsId,
            'c.status' => 1
        ]);
        $this->setTotal(['goodsId' => $goodsId, 'status' => 1]);
        $db->limit($limit, $offset);
        $db->order_by('c.created', 'DESC');
        $db->from('base_goods_comments as c');
        $db->join('user as u', 'u.id=c.userId');
        $query = $db->get();

        $rows = $query->result_array();

        if (!empty($rows)) foreach($rows as &$row) {
            $row['user'] = [];
            $row['created'] = formateTimeStamp($row['created']);
        }

        $this->getUsers($rows);

        return $rows;
    }

    private function setTotal($where)
    {
        $db = clone ($this->db);
        $db->where($where);
        $this->totalSize = $db->count_all_results('base_goods_comments');
    }

    /**
     * 评论对应用户
     * @param $comments
     */
    private function getUsers(&$comments)
    {
        if (empty($comments)) {
            return ;
        }

        $userIds = [];
        foreach ($comments as $comment) { $userIds[] = $comment['userId']; }
        unset($comment);
        if (empty($userIds)) { return ; }

        $userDB = clone($this->db);
        $userDB->select('u.id, u.nickName, p.avatar');
        $userDB->where_in('u.id', $userIds);
        $userDB->from('user as u');
        $userDB->join('user_profile as p', 'p.userId=u.id');
        $query = $userDB->get();
        $rows = $query->result_array();

        $users = [];
        if (!empty($rows)) foreach ($rows as $row) {
            $userId = $row['id'];
            $row['avatar'] = thumb($row['avatar'], 100, 100);
            $users[$userId] = $row;
        }

        foreach ($comments as &$comment) {
            $uid = $comment['userId'];
            if (array_key_exists($uid, $users)) {
                $comment['user'] = $users[$uid];
            }
        }

    }

}
